package com.wssnail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wssnail.aes.WXBizMsgCrypt;
import com.wssnail.constants.MsgType;
import com.wssnail.dto.ReceiveMessage;
import com.wssnail.dto.ReplyMessage;
import com.wssnail.mapper.WxOfficeMapper;
import com.wssnail.model.WxOffice;
import com.wssnail.service.WxOfficeService;
import com.wssnail.util.XMLParse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yan
 * @since 2022-09-28
 */
@Service
@Slf4j
public class WxOfficeServiceImpl extends ServiceImpl<WxOfficeMapper, WxOffice> implements WxOfficeService {

    @Value("${wssnail.wx.appId}")
    private String appId;
    @Value("${wssnail.wx.encoding_aes_key}")
    private String encodingAesKey;

    @Value("${wssnail.wx.token}")
    private String token;
    @Autowired
    private WxOfficeMapper wxOfficeMapper;

    @Override
    public String handleMsg(String timestamp, String nonce, HttpServletRequest request) {
        Map<String, String> map = XMLParse.xmlToMap(request);
        String encrypt = map.get("Encrypt");
        try {
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId);
            String decrypt = wxBizMsgCrypt.decrypt(encrypt);
            ReceiveMessage receiveMessage = XMLParse.xmlToBean(decrypt, ReceiveMessage.class);
            if (MsgType.EVENT.equals(receiveMessage.getMsgType())) {
                //事件
                WxOffice wxOffice = wxOfficeMapper.selectOne(new LambdaQueryWrapper<WxOffice>().eq(WxOffice::getKeyWord, receiveMessage.getEvent())
                        .eq(WxOffice::getStatus, 1).eq(WxOffice::getMsgType, 0));
                if (null != wxOffice) {
                    return getString(timestamp, nonce, wxBizMsgCrypt, receiveMessage, wxOffice, MsgType.TEXT);
                }
            } else if (MsgType.TEXT.equals(receiveMessage.getMsgType())) {
                WxOffice wxOffice = wxOfficeMapper.selectOne(new LambdaQueryWrapper<WxOffice>().eq(WxOffice::getKeyWord, receiveMessage.getContent())
                        .eq(WxOffice::getStatus, 1).eq(WxOffice::getMsgType, 1));
                //被动回复消息
                if (null != wxOffice) {
                    return getString(timestamp, nonce, wxBizMsgCrypt, receiveMessage, wxOffice, MsgType.TEXT);
                } else {
                    ReplyMessage replyMessage = new ReplyMessage();
                    replyMessage.setContent("您输入的内容我还无法识别，正在努力学习中哦");
                    replyMessage.setToUserName(receiveMessage.getFromUserName());
                    replyMessage.setFromUserName(receiveMessage.getToUserName());
                    replyMessage.setMsgType(MsgType.TEXT);
                    replyMessage.setCreateTime(new Date().getTime());
                    String s = XMLParse.beanToXML(replyMessage);
                    String result = wxBizMsgCrypt.encryptMsg(s, timestamp, nonce);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /*
     * @description:生成回复消息
     * @author: yan
     * @date: 2022/9/28 17:52
     * @param timestamp
     * @param nonce
     * @param wxBizMsgCrypt
     * @param receiveMessage
     * @param wxOffice
     * @return:
     * @return: java.lang.String
     **/
    private String getString(String timestamp, String nonce, WXBizMsgCrypt wxBizMsgCrypt,
                             ReceiveMessage receiveMessage, WxOffice wxOffice, String msgType) throws Exception {
        ReplyMessage replyMessage = new ReplyMessage();
        replyMessage.setContent(wxOffice.getReplyMsg());
        replyMessage.setToUserName(receiveMessage.getFromUserName());
        replyMessage.setFromUserName(receiveMessage.getToUserName());
        replyMessage.setMsgType(msgType);
        replyMessage.setCreateTime(new Date().getTime());
        String s = XMLParse.beanToXML(replyMessage);
        String result = wxBizMsgCrypt.encryptMsg(s, timestamp, nonce);
        log.info(">>>>>>>>>>>>>>>>>>>>加密后的内容:{}", result);
        return result;
    }

}
